//
//  MusicDownload.m
//  老司机发车了标准版
//
//  Created by SuperNing on 16/8/11.
//  Copyright © 2016年 斌. All rights reserved.
//

#import "MusicDownload.h"
#import "PlayerModel.h"
#import "MusicDataBase.h"

@interface MusicDownload ()<NSURLSessionDelegate,NSURLSessionDownloadDelegate>

@property (nonatomic, strong) NSURLSession *session;

@end

static MusicDownload *_musicDownload = nil;

@implementation MusicDownload

+ (instancetype)shareMusicDownload{
    
    MusicDownload *instance = [[MusicDownload alloc] init];
    instance.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:instance delegateQueue:[NSOperationQueue mainQueue]];
    
    // 打开数据库
    [[MusicDataBase shareMusicDataBase] openDB];
    // 建表
    [[MusicDataBase shareMusicDataBase] createTableWithTableName:@"downloadTable"];
    
    return instance;
}

- (void)createDownloadTask:(PlayerModel *)playermodel{
    
    NSURLSessionDownloadTask *downloadTask = [_session downloadTaskWithURL:[NSURL URLWithString:playermodel.file_link]];
//    NSURLSessionDownloadTask *downloadTask2 = [_session down]
    
    
    [[MusicDataBase shareMusicDataBase] insertDataWithModel:playermodel];
    
    [downloadTask resume];
}

// 完成下载时
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    
    NSFileManager *manager = [NSFileManager defaultManager];
    
    NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    NSString *filePath = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@",downloadTask.response.suggestedFilename]];
    NSLog(@"%@", filePath);
    
    BOOL success = [manager moveItemAtPath:location.path toPath:filePath error:nil];
    if (!success) {
        NSLog(@"文件已存在在或文件出错");
    }
    
}


// 写入过程中会重复调用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    
    NSLog(@"progress = %f", ((float)totalBytesWritten / totalBytesExpectedToWrite));
    
    
}









@end
